<?php
namespace app\api\controller;

use think\facade\Db;
use think\facade\Log;
use think\facade\Request;
use think\facade\Cache;

class AcceptVeriff
{
    private $redis;

    public function __construct()
    {
        $this->redis = Cache::store('redis')->handler();
    }

    public function webhkVeriff()
    {
        $params = Request::param();
        //记录日志
        $time   = getUtcTime(false);
        Log::write($params);
        Log::write("\n");

        if(!is_array($params)){
            $params = json_decode($params , true);
        }
        if(isset($params['verification']['id'])){
            $sessionId = $params['verification']['id'];
            $status    = $params['verification']['status'];
            $id_number = $params['verification']['document']['number'] ?? '';
            $list = Db::name('user_veriff')->where('session_id', $sessionId)->find();
            if($list){
                $id         = $list['id'];
                $name       = $list['name'];
                $user_id       = $list['user_id'];
                Db::name('user_veriff')->where('id', $id)
                    ->update([
                        'is_rep' => $status,
                        'id_number' => $id_number,
                    ]);
                if($status == 'approved'){
                    Db::name('user')->where('id', $user_id)
                        ->update([
                            'name' => $name,
                            'grade'=>1,
                            'grade_new'=>3,
                            'id_card' => $id_number
                        ]);
                }
            }
        }
        http_response_code(200);
        echo "success";
    }

    public function callback()
    {
        // 1. 获取原始 JSON
//        $raw = file_get_contents("php://input");
        $params = Request::param();
        // 2. 写入日志（调试用）
        Log::write("Veriff callback raw: " . $params, 'info');

        // 3. 转数组
        $data = json_decode($params, true);
        if (!$data) {
            return json(['status' => 'fail', 'msg' => 'json error']);
        }

        // -------------------------
        // 示例数据访问方式
        // -------------------------
        $verificationId = $data['verification']['id'] ?? null;
        $status         = $data['verification']['status'] ?? null; // approved/declined
        $reason         = $data['verification']['reason'] ?? null;

        // 4. 业务逻辑（你可以在这里更新数据库）
        // Db::name('user_verification')->where('veriff_id', $verificationId)->update([...]);

        // 5. 必须返回 200
        return json(['ok' => 1]);
    }
}
